'use client'

import { useEffect, useState } from 'react'
import { VmsCopy } from '@/types/Model'
import { useParams, useRouter } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import TailwindAdvancedEditor from "@/components/tailwind/advanced-editor"

export default function CopyEditPage() {
  const { id } = useParams()
  const router = useRouter()
  const [copy, setCopy] = useState<VmsCopy | null>(null)
  const [loading, setLoading] = useState(true)

  const fetchCopy = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy/${id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to fetch copy details')
      }
      
      const data = await response.json()
      setCopy(data)
      
      toast({
        title: '数据获取成功',
        description: '文案详情已加载',
      })
    } catch (error) {
      console.error('Error fetching copy:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }
  const saveCopy = async (copy: VmsCopy) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(copy)
      })
      
      if (!response.ok) {
        throw new Error('Failed to save copy')
      }
      
      toast({
        title: '保存成功',
        description: '文案已成功保存',
      })
      
      // Optionally refresh the data
      await fetchCopy()
    } catch (error) {
      console.error('Error saving copy:', error)
      toast({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  useEffect(() => {
    if (id) {
      fetchCopy()
    }
  }, [id])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }

  if (!copy) {
    return <div>未找到文案</div>
  }

  return (
       <div className='flex justify-center w-full py-8'>
         <TailwindAdvancedEditor 
            copy={copy}
            saveCopy={saveCopy}
        />
       </div>
  )
}
